<template>
  <div class="login">
    <h3> rbac 系统</h3>
    <el-tabs v-model="activeName">
      <el-tab-pane label="密码登录" name="first">
        <el-form label-position="right" label-width="80px" :model="user" :rules="rules">
          <el-form-item label="账户" prop="userName">
            <el-input v-model="user.userName"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="userPassword">
            <el-input v-model="user.userPassword" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-row :gutter="24">
              <el-col :span="6" :offset="6">
                <el-button type="primary" @click="login">登录</el-button>
              </el-col>
              <el-col :span="6">
                <el-button @click="user={}">重置</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <!--分隔符-->
      <el-tab-pane label="短信登录" name="second">
        <el-form label-position="right" label-width="80px" status-icon
                 ref="smsForm" :model="sms" :rules="rules">
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="sms.phone"></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="18">
              <el-form-item label="验证码" prop="checkcode">
                <el-input v-model="sms.checkcode"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button :disabled="codeflag" @click.prevent="getCheckCode()">{{ codetxt }}</el-button>
            </el-col>
          </el-row>
          <el-form-item>
            <el-row :gutter="24">
              <el-col :span="6" :offset="6">
                <el-button type="primary" @click.prevent="loginSms">登录</el-button>
              </el-col>
              <el-col :span="6">
                <el-button @click="sms={}">重置</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import axios from '../utils/request'

export default {
  name: 'Login',
  data () {
    /**
     * @param rule
     * @param value 输入的文字
     * @param callback 回调函数
     */
    const validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入电话号码'))
      } else {
        // if (this.ruleForm.checkPass !== '') {
        //   this.$refs.ruleForm.validateField('checkPass')
        // }
        let regex = /^1[3,4,5,6,7,8,9]\d{9}$/
        if (regex.test(value) === false) {
          callback(new Error('请输入正确的手机格式'))
        } else {
          callback()
        }
      }
    }
    /**
     * @param rule
     * @param value 输入的文字
     * @param callback 回调函数
     */
    const validateCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'))
      } else {
        // if (this.ruleForm.checkPass !== '') {
        //   this.$refs.ruleForm.validateField('checkPass')
        // }
        let regex = /^\d{4}$/
        if (regex.test(value) === false) {
          callback(new Error('请输入正确的验证码格式'))
        } else {
          callback()
        }
      }
    }
    return {
      activeName: 'first',
      user: {},
      // 这种检查没有实施检查的功能
      rules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {min: 6, max: 12, message: '长度在6到12个字符', trigger: 'blur'}
        ],
        userPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          {validator: validatePhone, trigger: 'blur'}
        ],
        checkcode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          {validator: validateCode, trigger: 'blur'}
        ]
      },
      sms: {},
      codetxt: '发送验证码',
      codeflag: false
    }
  },
  methods: {
    async login () {
      // 此处不能使用this.$store.state.user是否为空进行判断，
      // 因为
      let response = await axios({
        method: 'post',
        url: '/admin/user/login',
        params: this.user
      })
      if (response.code === '200') {
        this.user = response.data
        console.log(this.user)
        // 此处不可以使用异步
        this.$store.commit('updateUser', this.user)
        // 跳转
        this.$router.push('/index')
      }
    },
    getCheckCode () {
      // 1 验证窗体电话好吗是否正常输入
      this.$refs['smsForm'].validateField('phone', async (valid) => {
        if (!valid) {
          let response = await axios({
            url: 'admin/sms/' + this.sms.phone,
            method: 'get'
          })
          if (response.code === '200') {
            this.codeflag = true
            let lasttime = 60
            this.codetxt = `倒计时${lasttime}秒`
            let id = window.setInterval(() => {
              if (lasttime < 0) {
                this.codeflag = false
                this.codetxt = '获取验证码'
                window.clearInterval(id)
                return
              }
              lasttime = lasttime - 1
              this.codetxt = `${lasttime}`
            }, 1000)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 点击短信登录的按钮
    loginSms () {
      // 1 验证窗体电话好吗是否正常输入
      this.$refs['smsForm'].validate(async (valid) => {
        if (valid) {
          let response = await axios({
            method: 'get',
            url: '/admin/sms/login',
            params: this.sms
          })
          if (response.code === '200') {
            this.$store.commit('updateUser', response.data)
            // 跳转
            this.$router.push('/index')
          } else {
            alert('注册失败，请重试')
          }
        } else {
          return false
        }
      }
      )
    }
  }
}
</script>

<style scoped>
.login {
  width: 500px;
  height: 350px;
  background-color: darkgrey;
  border: solid 1px #dcdfe6;
  border-radius: 10px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding-right: 40px;
}

.login h3 {
  text-align: center;
}
</style>
